package com.gitee.wsl.net.udp

import com.gitee.wsl.net.udp.api.Acceptor
import com.gitee.wsl.net.udp.connection.Connection
import com.gitee.wsl.net.udp.connection.MAX_IDLE_TIMEOUT
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

class KeepAliveTest {

    @Test
    fun keepAlive(): Unit = runBlocking(Dispatchers.IO) {


        val server = newUdpService(0, object : Acceptor {
            override suspend fun accept(
                connection: Connection
            ) {
            }
        }

        )
        val remoteAddress = server.localAddress()


        val connection = assertNotNull(
            connectUdp(
                remoteAddress, 1
            )
        )

        connection.enableKeepAlive()

        assertEquals(server.connections().size, 1)


        delay((MAX_IDLE_TIMEOUT + 2000).toLong())
        // now it should be no connections

        assertEquals(server.connections().size, 1)


        connection.close()
        server.shutdown()
    }
}